<template>
    <view class="page">
        <view class="photo">
            <van-uploader :file-list="fileList" accept="image" max-count="1" @after-read="afterRead"  />
            <!-- <view class='head_img' bindtap='upShopLogo'>
            <view class='img'>
                <image src='{{userimg}}'></image>
            </view>
        </view> -->
        </view>
        <view class="title-input">
            <view class="title-name">
                <van-field v-model="username" label="昵称" placeholder="请输入昵称" />
            </view>
            <view class="title-name">
                <van-field v-model="phone" label="手机号码" placeholder="手机号码" />
            </view>
            <view class="title-car">
                <span class="title-number">
                    <span class="title-text">车牌号码</span>
                </span>
                <span class="title-btn">
                    <van-icon name="plus" />
                    <span class="title-cartext" @tap.native="addCarnumber">添加车牌</span>
                </span>
            </view>
        </view>
        <!-- 车牌号码输入框 -->
        <view :data-id="index" v-for="(item, idx) in plateNumbers" :key="item.i">
            <view class="carNumber">
                <!-- 车牌号头两位 -->
                <view class="carNumber-items">
                    <!-- <view class="carNumber-items-box" bindtap='openKeyboard'>
                <view class="carNumber-items-province carNumber-items-box-list">
                    {{carnum[0] || ''}}
                </view>
                <view class="carNumber-items-En carNumber-items-box-list">{{carnum[1] || ''}}</view>
            </view> -->
                    <!-- 常规 -->
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 0 ? 'active' : '')" :data-idx="idx" :data-index="0" @tap="openKeyboard">
                        {{ plateNumbers[idx][0] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 1 ? 'active' : '')" :data-idx="idx" :data-index="1" @tap="openKeyboard">
                        {{ plateNumbers[idx][1] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 2 ? 'active' : '')" :data-idx="idx" :data-index="2" @tap="openKeyboard">
                        {{ plateNumbers[idx][2] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 3 ? 'active' : '')" :data-idx="idx" :data-index="3" @tap="openKeyboard">
                        {{ plateNumbers[idx][3] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 4 ? 'active' : '')" :data-idx="idx" :data-index="4" @tap="openKeyboard">
                        {{ plateNumbers[idx][4] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 5 ? 'active' : '')" :data-idx="idx" :data-index="5" @tap="openKeyboard">
                        {{ plateNumbers[idx][5] || '' }}
                    </view>
                    <view :class="'carNumber-item ' + (plate === idx && plateIndex === 6 ? 'active' : '')" :data-idx="idx" :data-index="6" @tap="openKeyboard">
                        {{ plateNumbers[idx][6] || '' }}
                    </view>
                    <!-- 新能源 -->
                    <view :class="'carNumber-item ' + (plateNumbers[idx][7] ? '' : 'carNumber-item-newpower')">
                        <view v-if="!plateNumbers[idx][7]" :data-idx="idx" :data-index="7" @tap="showPowerBtn">
                            <view class="carNumber-newpower-add">+</view>
                            <view>新能源</view>
                        </view>
                        <view v-if="plateNumbers[idx][7]" :data-idx="idx" :data-index="7" @tap="openKeyboard">
                            {{ plateNumbers[idx][7] }}
                        </view>
                    </view>
                    <view class="delete" :data-idx="idx" @tap="handleDelete">
                        <van-icon name="delete-o" size="40rpx" />
                    </view>
                </view>
            </view>
        </view>
        <!-- 虚拟键盘 -->
        <view class="keyboard" v-if="KeyboardState">
            <view class="keyboardClose">
                <view class="keyboardClose_btn" @tap="closeKeyboard">关闭</view>
            </view>
            <!-- 省份简写键盘 -->
            <view class="keyboard-item" v-if="plateIndex === 0">
                <view class="keyboard-line" v-for="(item, index) in provinces" :key="index">
                    <view class="keyboard-btn" :data-val="itemlist" :data-plate="plate" @tap="bindChoose" v-for="(itemlist, index1) in item" :key="index1">
                        {{ itemlist }}
                    </view>
                </view>
                <view class="keyboard-del" @tap="bindDelChoose">
                    <van-icon name="cross" style="margin-top: 10rpx" />
                    <!-- <text class="font_family icon-shanchu keyboard-del-font"></text> -->
                </view>
            </view>
            <!-- 车牌号码选择键盘 -->
            <view class="keyboard-item iscarnumber" v-else>
                <view class="keyboard-line" v-for="(item, index) in numbers" :key="index">
                    <view class="keyboard-btn" :data-val="itemlist" :data-plate="plate" @tap="bindChoose" v-for="(itemlist, index1) in item" :key="index1">
                        {{ itemlist }}
                    </view>
                </view>
                <view class="keyboard-del" @tap="bindDelChoose">
                    <van-icon name="cross" />
                </view>
            </view>
        </view>
        <view class="weui-cells__title">提示：暂时不支持临牌车辆</view>
        <!-- 提交车牌 -->
        <van-button type="info" class="carNumberBtn" @tap.native="submitNumber">保存</van-button>
    </view>
</template>

<script>
import util from './../../utils/util.js';
import api from './../../utils/api.js';
import { Dialog } from 'vant';
export default {
    data() {
        return {
            // 省份简写
            provinces: [
                ['京', '沪', '粤', '津', '冀', '晋', '蒙', '辽', '吉', '黑'],
                ['苏', '浙', '皖', '闽', '赣', '鲁', '豫', '鄂', '湘'],
                ['桂', '琼', '渝', '川', '贵', '云', '藏'],
                ['陕', '甘', '青', '宁', '新']
            ],
            // 车牌输入
            numbers: [
                ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
                ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K'],
                ['L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'],
                ['W', 'X', 'Y', 'Z', '港', '澳', '学']
            ],
            carnum: [],
            showNewPower: false,
            KeyboardState: false,
            username: '',
            plateNumbers: [[]],
            plate: 0,
            //第几个车牌
            plateIndex: -1,
            phone: '',
            fileList: [],
            url: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        this.getPersonInfoByIndentityId();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function() {}
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ methods: {
        afterRead(event) {
            const { file } = event.detail; // this.setData({ fileList: event.detail.file.url });
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式

            var that = this; //坑1： this需要这么处理

            uni.uploadFile({
                url: api.vueUpload,
                // 仅为示例，非真实的接口地址
                filePath: file.url,
                name: 'file',
                formData: {
                    user: 'test'
                },
                header: {
                    // "Content-Type": "multipart/form-data",
                    Authorization: uni.getStorageSync('AUTHORIZATION') //如果需要token的话要传
                },

                success(res) {
                    var data = JSON.parse(res.data);
                    that.setData({
                        url: data.data
                    });

                    if (data.data) {
                        util.request(api.getEncryPath + '?path=' + data.data, '', 'POST').then((res) => {
                            that.setData({
                                fileList: [
                                    {
                                        url: res
                                    }
                                ]
                            });
                        });
                    } // 上传完成需要更新 fileList
                }
            });
        },

        deleteFun(e) {
            this.setData({
                fileList: [],
                url: ''
            });
        },

        // 选中点击设置
        bindChoose(e) {
            var plate = this.plate;
            var index = this.plateIndex;
            var plateNumbers = this.plateNumbers;
            plateNumbers[plate][index] = e.target.dataset.val;
            this.setData({
                plateNumbers
            });

            if (index < 7) {
                index = index + 1;
                this.setData({
                    plateIndex: index
                });
            } else {
                this.setData({
                    KeyboardState: false,
                    plate: 0,
                    //第几个车牌
                    plateIndex: -1
                });
            }
        },

        bindDelChoose() {
            var plate = this.plate;
            var index = this.plateIndex;
            var plateNumbers = this.plateNumbers;
            plateNumbers[plate][index] = '';
            this.setData({
                plateNumbers
            });

            if (index > 0) {
                index = index - 1;
                this.setData({
                    plateIndex: index
                });
            }
        },

        showPowerBtn() {
            this.setData({
                showNewPower: true,
                KeyboardState: true
            });
        },

        closeKeyboard() {
            this.setData({
                KeyboardState: false
            });
        },

        openKeyboard(e) {
            this.setData({
                KeyboardState: true,
                plate: e.currentTarget.dataset.idx,
                plateIndex: e.currentTarget.dataset.index
            });
        },

        addCarnumber() {
            const plateNumberslength = (this.plateNumbers && this.plateNumbers.map((e) => e.join(''))) || [];

            for (let i = 0; i < plateNumberslength.length; i++) {
                if (plateNumberslength[i].length < 7) {
                    uni.showToast({
                        title: '请输入完整车牌',
                        icon: 'none'
                    });
                    return;
                }
            }

            let addItem = ['', '', '', '', '', '', '', ''];
            this.setData({
                plateNumbers: [...this.plateNumbers, addItem],
                KeyboardState: false
            });
        },

        //删除车牌号
        handleDelete(e) {
            if (e.currentTarget.dataset.idx == 0) {
                uni.showToast({
                    title: '请输入车牌号',
                    icon: 'none'
                });
                return;
            }

            const index = e.currentTarget.dataset.idx;
            this.plateNumbers.splice(index, 1);
            this.setData({
                plateNumbers: this.plateNumbers
            });
        },

        //保存  // 提交车牌号码
        submitNumber() {
            if (!this.username.replaceAll(' ', '')) {
                uni.showToast({
                    title: '请输入昵称',
                    icon: 'none'
                });
                return;
            }

            if (!this.phone.replaceAll(' ', '')) {
                uni.showToast({
                    title: '请输入手机号',
                    icon: 'none'
                });
                return;
            }

            const plateNumberslength = (this.plateNumbers && this.plateNumbers.map((e) => e.join(''))) || [];

            for (let i = 0; i < plateNumberslength.length; i++) {
                if (plateNumberslength[i].length < 7) {
                    uni.showToast({
                        title: '请输入完整车牌',
                        icon: 'none'
                    });
                    return;
                }
            }

            this.setupdateUser();
            this.setData({
                KeyboardState: false
            });
        },

        //获取个人资料
        getPersonInfoByIndentityId() {
            const unionId = uni.getStorageSync('unionId');
            util.request(api.PersonInfoByIndentityId + '?personUnionId=' + unionId, 'get').then((res) => {
                if (res.code == 0) {
                    this.setData({
                        username: res.data.name,
                        phone: res.data.phoneNumber,
                        plateNumbers: res.data.plateNos && res.data.plateNos.map((e) => e.split(''))
                    });
                }
            });
        },

        setupdateUser() {
            const identityId = uni.getStorageSync('identityId');
            const param = {
                loginName: this.phone,
                name: this.username,
                url: this.url,
                plates: this.plateNumbers && this.plateNumbers.map((e) => e.join('')),
                identityId: identityId
            };
            const plateNos = this.plateNumbers && this.plateNumbers.map((e) => e.join(''));
            let plateStr = plateNos.join(',');
            util.request(api.updateUser, param, 'POST').then((res) => {
                if (res.code == 0) {
                    uni.setStorage({
                        key: 'phoneNumber',
                        data: this.phone
                    }); //手机号

                    uni.setStorage({
                        key: 'plateNos',
                        data: plateStr
                    }); // 车牌号

                    uni.showToast({
                        title: '修改成功',
                        icon: 'success'
                    });
                    uni.navigateTo({
                        url: '../index/index'
                    });
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            });
        }
    }
};
</script>
<style>
@import './index.css';
</style>
